let http = require('./libraries/http');

let getContents = function(token, type, pageIndex, pageSize, whenDone, whenError){
    let path = `https://api.cnblogs.com/api/statuses/@${type}?pageIndex=${pageIndex}&pageSize=${pageSize}`;
    http.get(path, token, res => {        
        let jsonData = JSON.parse(res);
        let models = [];
        let no = 1;
        for(let index in jsonData){
            let model = {
                ico: type === 'mention' ? jsonData[index].IconName: jsonData[index].UserIconUrl,
                name: jsonData[index].UserDisplayName,
                userId: jsonData[index].UserId,
                time: jsonData[index].DateAdded.substring(0, 16).replace('T',' '),                
                selected: false,
            }

            let text = '';
            switch(type){
                case 'comment': 
                    model.id = jsonData[index].StatusId; 
                    text = jsonData[index].StatusContent;
                    break;
                case 'mention': 
                    model.id = jsonData[index].ContentId; 
                    text = jsonData[index].IngContent;
                    break;
                default: 
                    model.id = jsonData[index].Id; 
                    text = jsonData[index].Content;
                    break;
            }
            text = removeTagElement(removeTagAElement(removeAtElement(text)));
            model.text = text;

            if(typeof(jsonData[index].CommentCount) != "undefined"){
                model.commentInfo = `评论(${jsonData[index].CommentCount})`;
            }
     
            if(models.filter(m => m.id === model.id).length > 0){
                continue;
            }

            model.no = no++;
            models.push(model);
       }
       whenDone(models);
    }, error=>{
        whenError(error);
    });
}

let getComments = function(token, id, myInfo, whenDone, whenError){
    let path = `https://api.cnblogs.com/api/statuses/${id}/comments`;
    http.get(path, token, res=>{
        let jsonData = JSON.parse(res);
        let models = [];
        let no = 1;
        for(let index in jsonData){
            var model = {
                id: jsonData[index].Id,
                name: jsonData[index].UserDisplayName,
                ico: jsonData[index].UserIconUrl,
                time: jsonData[index].DateAdded.substring(0, 16).replace('T',' '),
                text: removeAtElement(jsonData[index].Content),
                aboutMe: jsonData[index].UserId == myInfo.spaceUserId || jsonData[index].Content.indexOf(myInfo.spaceUserId) != -1
            }
            model.no = no++;
            models.push(model);
        }
        whenDone(models);
    }, error=> whenError(error));
}

let getMyInfo = function(token, whenDone, whenError){
    let path = `https://api.cnblogs.com/api/users`;
    http.get(path, token, res=>{
        let jsonData = JSON.parse(res);
        let userModel = {
            userId: jsonData.UserId,
            spaceUserId: jsonData.SpaceUserID,
            blogId: jsonData.BlogId,
            displayName: jsonData.DisplayName,
            face: jsonData.Face,
            avatar: jsonData.Avatar,
            seniority: jsonData.Seniority,
            blogApp: jsonData.BlogApp
        };
        whenDone(userModel);
    }, error=> whenError(error));
}

let send = function(token, content, whenDone, whenError){
    let path = 'https://api.cnblogs.com/api/statuses';
    http.post(path, token, {"Content": content, "IsPrivate": false}, res => whenDone(res), error => whenError(error));
}

// 去掉 @user 周围的链接
function removeAtElement(text){
    let replaceStrs = [];
    let re = new RegExp('<a href="http://home.cnblogs.com/u/\\d+/" target="_blank">@.{2,20}</a>', 'g');
    while(true){
        let group = re.exec(text)
        if(group){
            let searchedStr = group[0];
            let userId = searchedStr.substr(35, searchedStr.indexOf('/" target=') - 35);
            let newStr = searchedStr.replace(new RegExp('<a href="http://home.cnblogs.com/u/\\d+/" target="_blank">'), `<span class="user" userid="${userId}">`).replace('</a>', '</span>');

            replaceStrs.push({
                searchedStr: searchedStr,
                newStr: newStr
            });
        }
        else{
            break;
        }
    }
    for(let item of replaceStrs){
        text = text.replace(item.searchedStr, item.newStr);
    }
    return text;
}

// 去掉tag周围的链接
function removeTagAElement(text){
    let replaceStrs = [];
    let re = new RegExp('<a href="/tag/.+?/" class="ing_tag">\\[.+?\\]</a>', 'g');
    while(true){
        let group = re.exec(text)
        if(group){
            let searchedStr = group[0];
            let newStr = searchedStr.replace(new RegExp('<a href="/tag/.+?/" class="ing_tag">'), '<span class="tag">').replace('</a>', '</span>');

            replaceStrs.push({
                searchedStr: searchedStr,
                newStr: newStr
            });
        }
        else{
            break;
        }
    }
    for(let item of replaceStrs){
        text = text.replace(item.searchedStr, item.newStr);
    }
    return text;
}

// 把非链接tag包含在span标签中
function removeTagElement(text){
    let replaceStrs = [];
    let re = new RegExp('\\[.+?\\]', 'g');
    while(true){
        let group = re.exec(text)
        if(group){
            let searchedStr = group[0];
            let newStr = searchedStr.replace('[', '<span class="tag">[').replace(']', ']</span>');

            replaceStrs.push({
                searchedStr: searchedStr,
                newStr: newStr
            });
        }
        else{
            break;
        }
    }
    for(let item of replaceStrs){
        text = text.replace(item.searchedStr, item.newStr);
    }
    return text;
}

exports.getContents = getContents;
exports.getComments = getComments;
exports.getMyInfo = getMyInfo;
exports.send = send;